#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/15
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from project.flasky import db
from project.define import db_logger


DataName = "出口记录"
TableName = "app_records_exit"


class RecordExit(db.Model):
    """
    离场记录
    """
    __tablename__ = TableName
    # 离场ID
    ExitID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 闸机名称
    GateName = db.Column(db.String(16), nullable=False)
    # 车型地感
    VehicleType = db.Column(db.String(16))
    # 车牌结果
    LicensePlate = db.Column(db.String(16), nullable=False)
    # 结果图片路径
    LicensePlateImg = db.Column(db.String(128))
    # 时租票号
    TicketNumber = db.Column(db.String(128))
    # 月租卡号
    CardNumber = db.Column(db.String(64))
    # 闸机消息
    GateMessage = db.Column(db.String(32))
    # 闸机温度
    GateTemp = db.Column(db.Float)
    # 通过结果
    Past = db.Column(db.Boolean)
    # 车位类型
    ParkingType = db.Column(db.String(16))
    # 离场时间
    GateTime = db.Column(db.DateTime)
    # 月租用户
    UserID = db.Column(db.Integer)
    # 删除状态
    Deleted = db.Column(db.Boolean, default=False)

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.GateName = kwargs.get('GateName')
        self.VehicleType = kwargs.get('VehicleType')
        self.LicensePlate = kwargs.get('LicensePlate')
        self.LicensePlateImg = kwargs.get('LicensePlateImg')
        self.TicketNumber = kwargs.get('TicketNumber')
        self.CardNumber = kwargs.get('CardNumber')
        self.GateTemp = kwargs.get('GateTemp')
        self.GateMessage = kwargs.get('GateMessage')
        self.Past = kwargs.get('Past')
        self.ParkingType = kwargs.get('ParkingType')
        self.GateTime = datetime.now()
        self.UserID = kwargs.get('UserID')

    def datetime_string(self, val):
        """
        datetime转换
        """
        if isinstance(val, datetime):
            return val.strftime('%Y/%m/%d %H:%M:%S')

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(name):
            val = getattr(self, name)
            if isinstance(val, datetime):
                return val.strftime('%Y/%m/%d %H:%M:%S')
            return val

        return dict([(c.name, convert_data(c.name)) for c in self.__table__.columns])

    @staticmethod
    def column_names():
        """
        标题
        """
        return {
            "GateTime":"時間","ExitID":"離場ID","GateName":"閘機名稱","VehicleType":"車型","LicensePlate":"車牌結果",
            "LicensePlateImg":"識別圖片","TicketNumber":"時租票號","CardNumber":"月租卡號","GateMessage":"通過消息",
            "Past":"通過狀態","ParkingType":"車位類型","GateTemp":"體溫"
        }

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        exit_id = kwargs.get('ExitID')
        if exit_id:
            return RecordExit.query.filter_by(ExitID=exit_id).first()

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(RecordExit, k):
                    if k == 'GateName':
                        filters.add(RecordExit.GateName == v)
                    elif k == "VehicleType":
                        filters.add(RecordExit.VehicleType == v)
                    elif k == "LicensePlate":
                        filters.add(RecordExit.LicensePlate.like(f"%{v}%"))
                    elif k == "TicketNumber":
                        filters.add(RecordExit.TicketNumber.like(f"%{v}%"))
                    elif k == "CardNumber":
                        filters.add(RecordExit.CardNumber.like(f"%{v}%"))
                    elif k == "ParkingType":
                        filters.add(RecordExit.ParkingType == v)
                    elif k == "GateTime":
                        if "-" in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(RecordExit.GateTime.between(start, end))
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = RecordExit(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = RecordExit.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")


